package com.xuebusi.xpress.admin.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

@Controller
@RequestMapping(value = "/admin")
public class HomeController {

    @RequestMapping
    public String home(Model model) {
        model.addAttribute("adminTile", "网站后台首页标题");
        model.addAttribute("adminContent", "网站后首页内容");
        return "admin/home";
    }

    @RequestMapping(value = "labelMapFormat", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject labelMapFormat(String base64img) {
        convert(base64img, 500, 500);
        JSONObject object = new JSONObject();
        object.put("data", "ok");
        return object;
    }

    public static void convert(String labelmapBase64, int realWidth, int realHeight) {
        try {

            byte[] bytes = Base64.getDecoder().decode(labelmapBase64);
            InputStream is = new ByteArrayInputStream(bytes);
            BufferedImage image = ImageIO.read(is);
            BufferedImage newImage = resize(image, realWidth, realHeight);
            BufferedImage grayImage = new BufferedImage(realWidth, realHeight, BufferedImage.TYPE_BYTE_GRAY);
            for(int i= 0 ; i < realWidth ; i++){
                for(int j = 0 ; j < realHeight; j++){
                    int rgb = newImage.getRGB(i, j);
                    grayImage.setRGB(i, j, rgb * 255);  //将像素存入缓冲区
                }
            }
            File newFile = new File("gray.jpg");
            ImageIO.write(grayImage, "jpg", newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static BufferedImage resize(BufferedImage img, int newW, int newH) {
        Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
        BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);

        Graphics2D g2d = dimg.createGraphics();
        g2d.drawImage(tmp, 0, 0, null);
        g2d.dispose();

        return dimg;
    }
}
